<?php

/**
 * 搜索
 *
 * @author 狐狸<foxis@qq.com>
 * @package jishigou.net
 */
if(!defined('IN_JISHIGOU'))
{
    exit('invalid request');
}

class ModuleObject extends MasterObject
{
	
	function ModuleObject($config)
	{
		$this->MasterObject($config);	
		
		Load::logic('topic');
		$this->TopicLogic = new TopicLogic($this);
		DatabaseHandler::$noCache =false;
		$this->Execute();
	}

	
		
	function Execute()
	{
		
		$load_file = array();
		switch ($this->Code) {
	  case 'topic':
				$this->TopicSearch();
				break;
		case 'tag':
				$this->TagSearch();
				break;
		case 'user':
				$this->UserSearch();
				break;
		case 'usertag':
				$this->UserTagSearch();
				break;
		case 'vote':
				$this->VoteSearch();
				break;
		default:
			$this->Main();
			break;
		}
	}
	
	function Main()
	{
		
		include($this->TemplateHandler->Template('search_list'));
	}
	
	function UserSearch()
	{ 
		$per_page_num = 10;
		$query_link = 'index.php?mod=search&code=user';
		$order = " order by `fans_count` desc "; 

		$keyword = trim($this->Get['user']);

		if ($keyword) {
			$url_key=urlencode($keyword);
			$search_keyword = $keyword;
			// $search_keyword = $this->Get['nickname'];
			if (strlen($keyword) < 2) {
				$this->Messager("请输入至少3个字符的关键词",-1);
			}
	
			$where_list['keyword'] = false!==strpos($keyword,'@') ? "`email`='".addslashes("{$keyword}")."'" : build_like_query("nickname",$keyword);
			$query_link .= "&keyword=" . urlencode($keyword);
			$where = (empty($where_list)) ? null : ' WHERE '.implode(' AND ',$where_list).' ';
		}	
		
		$province = $this->Get['province'];
		if($province) {
			$where_list['province'] = "`province`='".addslashes("{$province}")."'";
			$query_link .= "&province=" . urlencode($province);
			
			if (($city = $this->Get['city'])) {
				$where_list['city'] = "`city`='".addslashes("{$city}")."'";
				$query_link .= "&city=" . urlencode($city);
			}
			
			$where = (empty($where_list)) ? null : ' WHERE '.implode(' AND ',$where_list).' ';	
		}
	
				$tags = trim($this->Get['tags']);	
 		$tags = getSafeCode($tags);
 		if($tags) 
		{
			$search_keyword = $tags;
			
			if (strlen($tags) < 2) {
				$this->Messager("请输入至少2个字符的关键词",-1);
			}
			$sql = "select distinct(`uid`) as `uid` from `".TABLE_PREFIX."tag_favorite` where `tag` = '{$tags}' order by `id` desc ";
				$query = $this->DatabaseHandler->Query($sql);
				$uids = array();
				while ($row = $query->GetRow()) 
				{
					$uids[$row['uid']] = $row['uid'];
				}
			
				if(!empty($uids))
				{
					$where = $where_list = " where `uid` in (".implode(",",$uids).")";
					$query_link .= "&tags=" . urlencode($tags);
				}
		 }

				if($where_list)
		{
			$result = $this->_MemberList($where,true);
            extract($result);
            
						
			if($uids)
			{
			$sql = "select * from `".TABLE_PREFIX."user_tag_fields`where `uid` in (".implode(",",$uids).")";
				$query = $this->DatabaseHandler->Query($sql);
				$member_tag = array();
				while($row = $query->GetRow())
				{
					$member_tag[] = $row;
				}
			}
			
		}
	  
	  
		$this->Title = "用户搜索";
		include($this->TemplateHandler->Template('search_list'));
	}
	
    function UserTagSearch()
  {
        $per_page_num = 10;
		$query_link = 'index.php?mod=search&code=user';
		$order = " order by `fans_count` desc "; 

		 		$usertag = trim($this->Get['usertag']);	
 		$usertag = getSafeCode($usertag);
 		
		if($usertag) 
		{
			$search_keyword = $usertag;
			$url_key=urlencode($usertag);
			if (strlen($usertag) < 2) {
				$this->Messager("请输入至少2个字符的关键词",-1);
			}
			
 			 			$where = 'where'.build_like_query('`tag_name`',$usertag);
 			
	 		$sql = "select * from `".TABLE_PREFIX."user_tag_fields` {$where}";
			$query = $this->DatabaseHandler->Query($sql);
			$uids = array();
			$user_tag_fields = array();
			while($row = $query->GetRow())
			{ 
				$user_tag_fields[] = $row;
				$uids[$row['uid']] = $row['uid'];
			}	

			if(!empty($uids))
			{
				$where = $where_list = " where `uid` in (".implode(",",$uids).")";
				$query_link .= "&usertag=" . urlencode($usertag);
			}
		}
		
				if($where_list)
		{
			$result = $this->_MemberList($where,true);
			extract($result);
			
			if($uids)
			{
								$sql = "select * from `".TABLE_PREFIX."user_tag_fields`where `uid` in (".implode(",",$uids).")";
				$query = $this->DatabaseHandler->Query($sql);
				$member_tag = array();
				while($row = $query->GetRow())
				{
					$member_tag[] = $row;
				}
			}
		
						$mytag = $this->_MyUserTag(MEMBER_ID);
		}
		
				$mytag = $this->_MyUserTag(MEMBER_ID);
		
		$this->Title = "个人标签搜索";
		include($this->TemplateHandler->Template('search_list'));
 	}

	
		function TopicSearch()
	{
 		$per_page_num = 10;
		$query_link = 'index.php?mod=search&code=topic';
			 
		$starttime = strtotime($this->Get['starttime']);
		$endtime   = strtotime($this->Get['endtime']);
		
		$keyword = trim($this->Get['topic']);
		$keyword = getSafeCode($keyword);
		  $url_key=urlencode($keyword);
		$search_keyword = $keyword;
		  		$_GET['highlight'] = $search_keyword;
		if ($starttime) {
			$where_list['starttime'] = "`dateline` > '{$starttime}'";
			$query_link .= "&starttime=" . urlencode($starttime);
		}
			
		if ($endtime) {
			$endtime += 86400;
			$where_list['endtime'] = "`dateline` < '{$endtime}'";
			$query_link .= "&endtime=" . urlencode($endtime);
		}
		
		if($keyword) {
			$where_list['keyword'] = build_like_query('content,content2',$keyword);
   		$query_link .= "&topic=" . urlencode($keyword);
   	}
		$where = (empty($where_list)) ? null : ' WHERE '.implode(' AND ',$where_list).' ';	
		
		$order = 'order by `dateline` desc';

				if($where_list)
		{ 
			
			 			 $sql = " select count(*) as `total_record` from `".TABLE_PREFIX."topic` {$where} ";
			 $query = $this->DatabaseHandler->Query($sql);
			 extract($query->GetRow());
				
			 			 $page_arr = page($total_record,$per_page_num,$query_link,array('return'=>'array',));
			 $condition = " {$where} {$order} {$page_arr['limit']} ";
	 
			 			 $topic_list = $this->TopicLogic->Get($condition);	
			
				$topic_list_count = 0;
				if($topic_list)
				{
					$topic_list_count = count($topic_list);
					
					if(!$topic_parent_disable) 
					{
												$parent_id_list = array();
						foreach ($topic_list as $row) {
							if(0 < ($p = (int) $row['parent_id'])) {
								$parent_id_list[$p] = $p;
							}
							if (0 < ($p = (int) $row['top_parent_id'])) {
								$parent_id_list[$p] = $p;
							}
						}
						
						if($parent_id_list) {	
														$parent_list = $this->TopicLogic->Get($parent_id_list);
						}
											}
				}
		}
		
		$this->Title = "搜索微博";
		include($this->TemplateHandler->Template('search_list'));
	}
	
		
		function TagSearch()
	{
		$per_page_num = 10;
		$order = 'order by `dateline` desc';
		$query_link = 'index.php?mod=search&code=tag';
		
		$tag = trim($this->Get['tag']);
		$tag = getSafeCode($tag);
	
		if($tag)
		{ $url_key=urlencode($tag);
			$search_keyword = $tag;
			  			$_GET['highlight'] = $search_keyword;
		
			$where = 'where'.build_like_query('`name`',$tag);
   		
			$sql = "select `id` from `".TABLE_PREFIX."tag` {$where}";
			$query = $this->DatabaseHandler->Query($sql);
			$tag_id = array();
			while ($row = $query->GetRow()) 
			{
				$tag_id[$row['id']] = $row['id'];
			}
	
			if($tag_id)
			{
				$sql = "select `item_id` from `".TABLE_PREFIX."topic_tag` where `tag_id` in(".implode(",",$tag_id).")";
				$query = $this->DatabaseHandler->Query($sql);
				$topic_ids = array();
				while ($row = $query->GetRow()) 
				{
					$topic_ids[$row['item_id']] = $row['item_id'];
				}
					$where = $where_list = "where `tid` in('".implode("','",$topic_ids)."') ";
					$query_link .= "&tag=" . urlencode($tag);
			}
		} 
		
				if($where_list)
		{
			 			 $sql = " select count(*) as `total_record` from `".TABLE_PREFIX."topic` {$where} ";
			 $query = $this->DatabaseHandler->Query($sql);
			 extract($query->GetRow());
				
			 			
			 $page_arr = page($total_record,$per_page_num,$query_link,array('return'=>'array',));
			 $condition = " {$where} {$order} {$page_arr['limit']} ";
			
						 $topic_list = $this->TopicLogic->Get($condition);	
			
				$topic_list_count = 0;
				if($topic_list)
				{
					$topic_list_count = count($topic_list);
					
					if(!$topic_parent_disable) 
					{
												$parent_id_list = array();
						foreach ($topic_list as $row) {
							if(0 < ($p = (int) $row['parent_id'])) {
								$parent_id_list[$p] = $p;
							}
							if (0 < ($p = (int) $row['top_parent_id'])) {
								$parent_id_list[$p] = $p;
							}
						}
						
						if($parent_id_list) {	
														$parent_list = $this->TopicLogic->Get($parent_id_list);
						}
											}
				}
		}
	
		$this->Title = "话题搜索";
		include($this->TemplateHandler->Template('search_list'));
		
	}
	
	
	function VoteSearch()
	{
		$perpage = 10;
		$q = trim($this->Get['q']);
		$q = getSafeCode($q);
		$gets = array(
			'mod' => 'search',
			'code' => 'vote',
			'q' => $this->Get['q'],
		);
		$page_url = 'index.php?'.url_implode($gets);
		$count = 0;
		if (!empty($q)) {
			$url_key=urlencode($q);
			$search_keyword = $q;
			$where = ' '.build_like_query('v.subject', $q).' ';
			$order = " ORDER BY dateline DESC ";
			Load::logic("vote");
			$VoteLogic = new VoteLogic();
			$param = array(
				'where' => $where,
				'order' => $order,
				'page' => true,
				'perpage' => $perpage,
				'page_url' => $page_url,
			);
			$vote_info = $VoteLogic->find($param);
			$vote_list = array();
			$page_arr['html'] = '';
			$uid_ary = array();
			if (!empty($vote_info)) {
				$count = $vote_info['count'];
				$vote_list = $vote_info['vote_list'];
				$page_arr['html'] = $vote_info['page']['html'];
				$uid_ary = $vote_info['uids'];
			}
			
						
						if (!empty($uid_ary)) {
				$members = $this->TopicLogic->GetMember($uid_ary);
			}
		}
		$this->Title = '投票搜索';
		include($this->TemplateHandler->Template('search_list'));
	}
	
	
	function _MemberList($where='',$return_more = false)
	{
            $return = array();
            		
                        $member_list = array();
			
			$sql = "select count(*) as `total_record` from `".TABLE_PREFIX."members` {$where}";
			$query = $this->DatabaseHandler->Query($sql);
			extract($query->GetRow());
			if($total_record > 0) 
            {
                $return['total_record'] = $total_record;			 
             
    			$_config = array (
    				'return' => 'array',
    			);
    			
    			$page_arr = page($total_record,$per_page_num,$query_link,$_config);
                
                $return['page_arr'] = $page_arr;
                
    			$sql = "select `uid`,`ucuid`,`username`,`nickname`,`face_url`,`face`,`fans_count`,`topic_count`,`province`,`city`,`validate` from `".TABLE_PREFIX."members` {$where} {$order} {$page_arr['limit']}";
    			$query = $this->DatabaseHandler->Query($sql);
    			$uids = array();
    			while ($row = $query->GetRow()) 
    			{
    				$row['face'] = face_get($row);
    				$member_list[$row['uid']] = $row;
    				$uids[$row['uid']] = $row['uid'];
    			}
    		
    			if($uids && MEMBER_ID>0) 
                {
    				$sql = "select `buddyid` as `id` from `".TABLE_PREFIX."buddys` where `uid`='".MEMBER_ID."' and `buddyid` in(".implode(",",$uids).")";
    				$query = $this->DatabaseHandler->Query($sql);
    				$buddys = array();
    				while ($row = $query->GetRow())
    				{
    					$buddys[$row['id']] = $row['id'];
    				}
    				
    				foreach ($uids as $uid) 
                    {
    					$member_list[$uid]['follow_html'] = follow_html($uid,isset($buddys[$uid]));	
    				}
    		  }		  
		}
        $return['member_list'] = $member_list;
        
        if($return_more)
        {
            return $return;
        }
		
		return $member_list;
	
	}
	

		function _MyUserTag($uid)
	{
		$sql = "select * from `".TABLE_PREFIX."user_tag_fields`where `uid` = '{$uid}'";
		$query = $this->DatabaseHandler->Query($sql);
		$mytag = array();
		$mytag_ids = array();
		while($row = $query->GetRow())
		{
			$mytag[] = $row;
			$mytag_ids[$row['tag_id']] = $row['tag_id'];
		}
			
		return $mytag;
	}
	
	
}
?>
